package com.bigmi.schedule.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bigmi.common.cont.ScheduleConstants;
import com.bigmi.common.redis.CacheService;
import com.bigmi.model.schedule.dto.Task;
import com.bigmi.model.schedule.pojos.Taskinfo;
import com.bigmi.model.schedule.pojos.TaskinfoLogs;
import com.bigmi.schedule.mapper.TaskinfoLogsMapper;
import com.bigmi.schedule.mapper.TaskinfoMapper;
import com.bigmi.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;


    /**
     * 添加延时任务
     * @return
     */
    @Override
    public long addTask(Task task) {
        //添加任务到数据库中
        boolean success= addTaskToDb(task);

        if (success){
            //添加任务到redis中
            addTaskToCache(task);
        }

        return task.getTaskId();
    }



    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag =false;
        try {
            //保存任务表
            Taskinfo taskinfo =new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //设置task——id
            task.setTaskId(taskinfo.getTaskId());
            //保存任务日志表
            TaskinfoLogs taskinfoLogs =new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            //乐观锁版本号
            taskinfoLogs.setVersion(1);
            //状态 0=初始化 1=执行成功 2=取消
            //默认设为初始化
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * 添加任务到redis中
     */
    private void addTaskToCache(Task task) {
        //key=任务执行类型+当前优先级
        String key =task.getTaskType()+"_"+task.getPriority();

        //获取五分钟之后的时间 毫秒值 创建日期对象
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long timeInMillis = calendar.getTimeInMillis();
        //如果任务时间小于等于当前时间存入list中
        if (task.getExecuteTime()<= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
            //如果任务大于当前时间并且小于等于预设时间(5分钟)存入zset中
        }else if (task.getExecuteTime()<=timeInMillis){
            //2.2 如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }


    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);

        //删除redis的数据
        if(task != null){
            removeTaskFromCache(task);
            flag = true;
        }
        return false;
    }

    /**
     * 删除redis中的任务数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务表数据，更新任务日志表状态
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("task cancel exception taskid={}",taskId);
        }

        return task;

    }
    /**
     * 消费任务，在list中拉取
     *按照类型和优先级拉取任务
     */
    @Override
    public Task poll(int type, int priority) {
        Task task=null;
        try {
            //key=任务执行类型+当前优先级
            String key =type+"_"+priority;
            //从redis中拉取
            String pop = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(pop)){
                task = JSON.parseObject(pop, Task.class);
                //修改数据库信息
                //已执行状态
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {

            e.printStackTrace();
            log.error("拉取任务异常");
        }
        return task;
    }

    /**
     *未来数据每分钟刷新一次
     */
    //定时任务每分钟执行一次
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        //System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");
        long l = System.currentTimeMillis() / 1000;
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(l);
        System.out.println("未来数据set 放入当前list数据开始执行"+currentTime+"执行了任务");
        // 获取所有未来数据集合的key值
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
        for (String futureKey : futureKeys) { // future_250_250
            //截取FUTURE中的值 future_100_50 截取100_50

            String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
            //获取该组key下当前需要消费的任务数据
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
            if (!tasks.isEmpty()) {
                //将这些任务数据添加到消费者队列中  从zset添加到list中
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
            }
        }
    }
    /**
     * 数据库任务定时同步到redis中
     */
    //启动服务的时候直接执行此任务
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        log.info("数据同步redis任务开始执行");
        //清理缓存中数据list zset,避免重复数据
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
        //查询符合条件的数据，小于未来五分钟的数据
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        LambdaQueryWrapper<Taskinfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.lt(Taskinfo::getExecuteTime,calendar.getTime());
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(queryWrapper);
        //把任务添加到redis中
        if (taskinfos!=null && taskinfos.size()>0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task =new Task();
                //添加任务调用add方法
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
        log.info("数据库任务同步到redis");
    }

}
